
from minio import Minio
from minio.error import S3Error
import hashlib

class MinIOHandler:
    def __init__(self, endpoint, access_key, secret_key):
        self.client = Minio(
            endpoint,
            access_key=access_key,
            secret_key=secret_key,
            secure=True
        )
    
    def create_bucket(self, bucket_name):
        """创建存储桶并返回操作状态"""
        try:
            if not self.client.bucket_exists(bucket_name):
                self.client.make_bucket(bucket_name)
                return f"Bucket {bucket_name} created"
            return "Bucket already exists"
        except S3Error as e:
            return f"Error: {e}"

    def upload_with_metadata(self, bucket, object_name, file_path):
        """带MD5校验的文件上传"""
        try:
            md5 = self._calculate_md5(file_path)
            self.client.fput_object(
                bucket,
                object_name,
                file_path,
                metadata={"Content-MD5": md5}
            )
            return f"File {object_name} uploaded with MD5: {md5}"
        except S3Error as e:
            return f"Upload failed: {e}"

    def generate_presigned_url(self, bucket, object_name, expiry=3600):
        """生成临时访问链接"""
        try:
            return self.client.presigned_get_object(
                bucket,
                object_name,
                expires=expiry
            )
        except S3Error as e:
            return f"URL generation failed: {e}"

    def _calculate_md5(self, file_path):
        """计算文件MD5值"""
        hash_md5 = hashlib.md5()
        with open(file_path, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        return hash_md5.hexdigest()

if __name__ == "__main__":
    akey="Hm1SboqyZtV8zT8y6m4j"
    skey="YXFtp5Fp7OitfiQEmUDKEDQLDkf76BD0e20mznvN"
    handler = MinIOHandler(
        "221.178.158.198:9001",
        akey,
        skey
    )
    print(handler.create_bucket("test-bucket-001"))
